package com.sgcc.pms.getway.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;

import com.sgcc.pms.getway.handler.JsonServerAuthenticationFailureHandler;
import com.sgcc.pms.getway.handler.JsonServerAuthenticationSuccessHandler;
import com.sgcc.pms.getway.handler.JsonServerLogoutSuccessHandler;

@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {

//	@Autowired
//	private AuthenticationConverter authenticationConverter;

//	@Autowired
//	private AuthorizeConfigManager authorizeConfigManager;

//	@Autowired
//	private AuthEntryPointException serverAuthenticationEntryPoint;

	@Autowired
	private JsonServerAuthenticationSuccessHandler jsonServerAuthenticationSuccessHandler;

	@Autowired
	private JsonServerAuthenticationFailureHandler jsonServerAuthenticationFailureHandler;

	@Autowired
	private JsonServerLogoutSuccessHandler jsonServerLogoutSuccessHandler;

//	@Autowired
//	private AuthenticationManager authenticationManager;

	private static final String[] AUTH_WHITELIST = new String[]{"/login", "/logout"};
	
	public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity httpSecurity) {
		httpSecurity.formLogin()
			.loginPage("/login")
			// 登录成功handler
			.authenticationSuccessHandler(jsonServerAuthenticationSuccessHandler)
			// 登陆失败handler
			.authenticationFailureHandler(jsonServerAuthenticationFailureHandler)
//			// 无访问权限handler
//			.authenticationEntryPoint(serverAuthenticationEntryPoint)
			.and()
			.logout()
			// 登出成功handler
			.logoutSuccessHandler(jsonServerLogoutSuccessHandler)
			.and()
			.csrf().disable()
			.httpBasic().disable()
			.authorizeExchange()
			// 白名单放行
			.pathMatchers(AUTH_WHITELIST).permitAll()
			// 访问权限控制
//			.anyExchange().access(authorizeConfigManager)
			.and().build();
		return httpSecurity.build();
	}
	
}
